import request from '@/utils/request'

import {
  Notification,
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import {
  tansParams,
  blobValidate
} from "@/utils/ruoyi";
import errorCode from '@/utils/errorCode'
import {
  saveAs
} from 'file-saver'

let downloadLoadingInstance

// 通用下载
export const commonDownload = (params) => {
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  })

  return request({
    url: '/common/download',
    method: 'get',
    params,
    responseType: 'blob'
  }).then(async data => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, params.fileName)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch(err => {
    downloadLoadingInstance.close();
  })
}
